const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const router = express.Router();

// 确保上传目录存在
const baseDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(baseDir)) {
    fs.mkdirSync(baseDir, { recursive: true });
}

// 配置multer存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
      // 从请求体中获取路径
      const uploadPath = req.body.path ? path.join(baseDir, req.body.path) : baseDir;
      if (!fs.existsSync(uploadPath)) {
          fs.mkdirSync(uploadPath, { recursive: true });
      }
      cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
      // 保留原始文件名
      cb(null, file.originalname);
  }
});

const upload = multer({ 
    storage: storage,
    limits: {
        fileSize: 100 * 1024 * 1024 // 限制文件大小为100MB
    },
    fileFilter: (req, file, cb) => {
        cb(null, true);
    }
});

// 获取文件列表
router.get('/', (req, res) => {
    const relativePath = req.query.path || '';
    const fullPath = path.join(baseDir, relativePath);
    
    if (!fs.existsSync(fullPath)) {
        return res.status(404).json({ error: '目录不存在' });
    }

    fs.readdir(fullPath, (err, items) => {
        if (err) {
            return res.status(500).json({ error: '无法读取目录内容' });
        }
        
        const files = [];
        const folders = [];
        
        items.forEach(item => {
            const itemPath = path.join(fullPath, item);
            const stats = fs.statSync(itemPath);
            
            if (stats.isDirectory()) {
                folders.push({
                    name: item,
                    path: path.join(relativePath, item)
                });
            } else {
                files.push({
                    name: item,
                    size: formatFileSize(stats.size),
                    uploadTime: stats.birthtime,
                    downloadLink: `/api/files/download/${encodeURIComponent(item)}?path=${encodeURIComponent(relativePath)}`
                });
            }
        });
        
        res.json({ files, folders });
    });
});

// 文件上传
router.post('/upload', upload.array('files'), (req, res) => {
    console.log('请求体内容:', req.body); // 查看整个请求体
    console.log('接收到的上传路径:', req.body.path || '根目录');
    
    if (!req.files || req.files.length === 0) {
        return res.status(400).json({ error: '没有文件被上传' });
    }
    
    // 获取上传路径
    const uploadPath = req.body.path || '';
    const fullPath = path.join(baseDir, uploadPath);
    console.log('完整保存路径:', fullPath);
    
    // 验证文件保存位置
    const results = req.files.map(file => {
        const expectedPath = path.join(fullPath, file.originalname);
        const actualPath = file.path;
        
        console.log(`文件 ${file.originalname}:`);
        console.log('预期路径:', expectedPath);
        console.log('实际路径:', actualPath);
        
        // 检查文件是否真的在预期路径
        const isInCorrectPath = actualPath.startsWith(fullPath);
        console.log('是否保存在正确路径:', isInCorrectPath);
        
        return {
            name: file.originalname,
            size: formatFileSize(file.size),
            expectedPath: expectedPath,
            actualPath: actualPath,
            isInCorrectPath: isInCorrectPath
        };
    });
    
    res.json({ 
        message: '文件上传结果',
        details: results,
        expectedBasePath: fullPath
    });
});

// 文件下载
router.get('/download/:filename', (req, res) => {
    const filename = decodeURIComponent(req.params.filename);
    const relativePath = req.query.path || '';
    const filePath = path.join(baseDir, relativePath, filename);
    
    if (!fs.existsSync(filePath)) {
        return res.status(404).json({ error: '文件不存在' });
    }
    
    res.download(filePath, filename, (err) => {
        if (err) {
            console.error('下载错误:', err);
            res.status(500).json({ error: '文件下载失败' });
        }
    });
});

// 删除文件
router.delete('/:filename', (req, res) => {
    const filename = decodeURIComponent(req.params.filename);
    const relativePath = req.query.path || '';
    const filePath = path.join(baseDir, relativePath, filename);
    
    if (!fs.existsSync(filePath)) {
        return res.status(404).json({ error: '文件不存在' });
    }
    
    fs.unlink(filePath, (err) => {
        if (err) {
            return res.status(500).json({ error: '删除文件失败' });
        }
        res.json({ message: '文件删除成功' });
    });
});

// 创建文件夹
router.post('/folder', (req, res) => {
    const { name, path: relativePath = '' } = req.body;
    if (!name) {
        return res.status(400).json({ error: '文件夹名称不能为空' });
    }
    
    const fullPath = path.join(baseDir, relativePath, name);
    
    if (fs.existsSync(fullPath)) {
        return res.status(400).json({ error: '文件夹已存在' });
    }
    
    fs.mkdir(fullPath, { recursive: true }, (err) => {
        if (err) {
            return res.status(500).json({ error: '创建文件夹失败' });
        }
        res.json({ message: '文件夹创建成功', path: fullPath });
    });
});

// 删除文件夹
router.delete('/folder/:foldername', (req, res) => {
    const foldername = decodeURIComponent(req.params.foldername);
    const relativePath = req.query.path || '';
    const folderPath = path.join(baseDir, relativePath, foldername);
    
    if (!fs.existsSync(folderPath)) {
        return res.status(404).json({ error: '文件夹不存在' });
    }
    
    // 检查文件夹是否为空
    const files = fs.readdirSync(folderPath);
    if (files.length > 0) {
        return res.status(400).json({ error: '文件夹不为空，无法删除' });
    }
    
    fs.rmdir(folderPath, (err) => {
        if (err) {
            return res.status(500).json({ error: '删除文件夹失败' });
        }
        res.json({ message: '文件夹删除成功' });
    });
});

// 辅助函数：格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

module.exports = router;